import sys
import os

#------------------------
#add lib path to sys.path
#------------------------
path=os.path.dirname(__file__)
path=os.path.join(path,'..', 'lib')
path=os.path.abspath(path)

sys.path.append(path)

import unittest
import SocketServer
import BaseHTTPServer
import threading
import sqlite3

import builderPie.demjson as json
import builderPie.clientFunctions
import builderPie.serverFunctions

class mockServer(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_POST(self):
        #get the post data
        length=int(self.headers.getheader('content-length'))
        rawPost=self.rfile.read(length)

        #output file object
        self.wfile.write(rawPost)


class testClientFunctions(unittest.TestCase):
    def test_communicate(self):
        #make sure that when you call the function with no server running
        #that it returns and empty list
        results=builderPie.clientFunctions.communicate(
            'localhost',
            8080,
            'test'
        )
        
        assert results==[]

        #setup mock server and make sure that what you send
        #is what you get back
        server=mockServer
        socket=SocketServer.TCPServer(('localhost', 8080), server)

        t = threading.Thread(target=socket.serve_forever)
        t.start()
        
        obj={"method": "getBuildList", "params": [], "id": 'a'}
        rpcJSON=json.encode(obj)

        results=builderPie.clientFunctions.communicate(
            'localhost',
            8080,
            rpcJSON
        )
        
        t.join(0)
        
        assert results==obj
        
class testServerFunctions(unittest.TestCase):
    def setUp(self):
        builderPie.serverFunctions.conn=sqlite3.connect('test.db')
        builderPie.serverFunctions.conn.row_factory=sqlite3.Row
        
        self.conn=builderPie.serverFunctions.conn
    
    def tearDown(self):
        builderPie.serverFunctions.conn.close()
        os.remove('test.db')
    
    def test_tableExists(self):
        self.conn.execute('create table test (test integer)')
        self.conn.commit()
        
        assert builderPie.serverFunctions.tableExists('test')
        
    def test_getBuildInfo(self):
        results=builderPie.serverFunctions.getBuildInfo('')
        
        assert results[1]['message'] == "No active builds available."
        
        obj={'params': {'buildName': 'test'}}
        
        builderPie.serverFunctions.initActiveBuilds()
        
        data=('test','test','test',json.encode(['test']),json.encode(['test']))
        
        columns="name, method, location, buildInfo, testInfo"
        sql='insert into activeBuilds (%s) values(?, ?, ?, ?, ?)' % columns
        
        self.conn.execute(sql, data)

        results=builderPie.serverFunctions.getBuildInfo(obj)
        
        assert len(results[0]) == 5
        assert results[0]['testInfo'] == ['test']
        assert results[0]['buildInfo'] == ['test']
        assert results[0]['id'] == 1
        assert results[0]['location'] == 'test'

    def test_postResults(self):
        assert 200 == 201, 'test not implemented yet'

    def test_serveBuildStats(self):
        assert 300 == 301, 'test not implemented yet'

    def test_serveRoot(self):
        assert 400 == 401, 'test not implemented yet'

    def test_serveDetails(self):
        assert 500 == 501, 'test not implemented yet'
        

if __name__ == '__main__':
	unittest.main()